package com.csu.letaobackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.letaobackend.bean.Item;
import com.csu.letaobackend.bean.Refundservice;
import com.csu.letaobackend.bean.Shop;
import com.csu.letaobackend.commom.CommonResponse;
import com.csu.letaobackend.persistence.ItemDao;
import com.csu.letaobackend.persistence.ShopDao;
import com.csu.letaobackend.service.ShopService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@MapperScan("com.csu.letaobackend.persistence")
public class ShopServiceImpl implements ShopService {
      @Autowired
      ShopDao shopDao;
      @Autowired
      ItemDao itemDao;

      @Override
      public CommonResponse<List<Shop>> getShopsBySeller(String username) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("sellername",username);

            List<Shop> shopList = shopDao.selectList(queryWrapper);
            return  CommonResponse.createForSuccess(shopList);
      }

      @Override
      public CommonResponse<Shop> getShops(int shopid) {
            return CommonResponse.createForSuccess(shopDao.selectById(shopid));
      }

      @Override
      public CommonResponse<List<Shop>> addShop(Shop shop) {
            shop.setSalesvolume(0);
            shop.setFavorablerate(5);
            shop.setShopid(getMaxShopId()+1);
            shopDao.insert(shop);
            return getShopsBySeller(shop.getSellername());
      }

      @Override
      public CommonResponse<Shop> updateShop(Shop shop) {
            shopDao.updateById(shop);
            return CommonResponse.createForSuccess(shopDao.selectById(shop.getShopid()));
      }

      @Override
      public CommonResponse<String> addItem(Item item) {
            itemDao.insert(item);
            return CommonResponse.createForSuccessMessage("add item successfully");
      }

      private int getMaxShopId() {
            List<Integer> list = new ArrayList<>();
            for (Shop shop : shopDao.selectList(null)) {
                  list.add(shop.getShopid());
            }
            if (list.size() == 0)
                  return 0;
            return Collections.max(list);
      }
}
